package dynamic.ibatis.scripting.xmltags;

/*
 *    Copyright 2009-2023 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */


import dynamic.ibatis.executor.parameter.DParameterHandler;
import dynamic.ibatis.mapping.DBoundSql;
import dynamic.ibatis.mapping.DMappedStatement;
import dynamic.ibatis.mapping.DSqlSource;
import dynamic.ibatis.scripting.DLanguageDriver;
import dynamic.ibatis.scripting.defaults.DDefaultParameterHandler;
import dynamic.ibatis.scripting.defaults.DRawSqlSource;
import dynamic.ibatis.session.DConfiguration;
import org.apache.ibatis.builder.xml.XMLMapperEntityResolver;
import org.apache.ibatis.parsing.PropertyParser;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;


/**
 * @author Eduardo Macarron
 */
public class DXMLLanguageDriver implements DLanguageDriver {

    @Override
    public DParameterHandler createParameterHandler(DMappedStatement mappedStatement, Object parameterObject,
                                                    DBoundSql boundSql) {
        return new DDefaultParameterHandler(mappedStatement, parameterObject, boundSql);
    }

    @Override
    public DSqlSource createSqlSource(DConfiguration configuration, XNode script, Class<?> parameterType) {
        DXMLScriptBuilder builder = new DXMLScriptBuilder(configuration, script, parameterType);
        return builder.parseScriptNode();
    }

    @Override
    public DSqlSource createSqlSource(DConfiguration configuration, String script, Class<?> parameterType) {
        // issue #3
        if (script.startsWith("<script>")) {
            XPathParser parser = new XPathParser(script, false, configuration.getVariables(), new XMLMapperEntityResolver());
            return createSqlSource(configuration, parser.evalNode("/script"), parameterType);
        }
        // issue #127
        script = PropertyParser.parse(script, configuration.getVariables());
        TextSqlNode textSqlNode = new TextSqlNode(script);
        if (textSqlNode.isDynamic()) {
            return new DDynamicSqlSource(configuration, textSqlNode);
        } else {
            return new DRawSqlSource(configuration, script, parameterType);
        }
    }

}
